const express = require('express');
const { routeWrapper } = require('../../lib/module/tool/route');
const router = express.Router();
const uuid = require('uuid');
const security = require('../../lib/service/security');
const orderPayment = require('../../lib/service/payment/orderPaymet');
const creditPaymet = require('../../lib/service/payment/creditPaymet');

// 生成支付签名参数
router.get('/:prepay_id/pay_params', routeWrapper(async (req) => {
    let payDict = {
        timeStamp: Math.round(new Date().getTime() / 1000).toString(),
        nonceStr: uuid.v1().toString().replace(/-/g, ''),
        package: 'prepay_id=' + req.params.prepay_id,
        signType: 'HMAC-SHA256'
    };
    // 生成签名
    payDict.paySign = security.generatePaySign(payDict);
    return payDict;
}, true));

// 支付回调
router.post('/ordernotify', routeWrapper(async (req, res) => {
    res.setHeader('content-type', 'application/xml');
    return orderPayment.orderPaymentNotify(req.body);
}, false));

// 退款回调
router.post('/:orderId/:refundId/orderrefundnotify', routeWrapper(async (req, res) => {
    res.setHeader('content-type', 'application/xml');
    return orderPayment.orderRefundNotify(req.params.orderId, req.params.refundId, req.body);
}));

// 信用金支付回调
router.post('/creditOrderNotify', routeWrapper(async (req, res) => {
    res.setHeader('content-type', 'application/xml');
    return creditPaymet.orderPaymentNotify(req.body);
}, false));

module.exports = {
    basePath: '/payment',
    router: router
};
